package com.eascs.ant.user.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eascs.ant.common.service.BaseSevice;
import com.eascs.ant.user.entity.User;
import com.eascs.ant.user.entity.UserStructure;
import com.eascs.ant.user.view.UserStructureView;
import com.eascs.common.util.StringUtil;

@Service
public class UserStructureService extends BaseSevice {

	@Inject
	private UserService userService;

	public List<UserStructure> getAllUserStructure() {
		return this.proxyDao.findAllEntitys(UserStructure.class);
	}

	@Transactional(transactionManager = "ticketTransactionManager")
	public void insertUserStructure(UserStructure userStructure) {
		UserStructure userStructureDelete = new UserStructure();
		userStructureDelete.setUserCode(userStructure.getUserCode());
		this.proxyDao.deleteEntitysWithAny(userStructureDelete);

		if (StringUtil.hasText(userStructure.getParentUserCode()))
			this.proxyDao.insert(userStructure);
	}

	public List<UserStructureView> getAllUserStructureViews() {
		List<User> users = userService.getAllUser();
		List<UserStructure> userStructures = this.getAllUserStructure();
		Map<String, UserStructureView> userStructureViewMap = new HashMap<>();
		for (User user : users) {
			userStructureViewMap.put(user.getCode(), new UserStructureView(user.getCode(), user.getName()));
		}
		for (UserStructure userStructure : userStructures) {
			UserStructureView userStructureView = userStructureViewMap.get(userStructure.getUserCode());
			UserStructureView parentUserStructureView = userStructureViewMap.get(userStructure.getParentUserCode());
			userStructureView.setParent(parentUserStructureView);
			parentUserStructureView.getChildren().add(userStructureView);
		}
		List<UserStructureView> userStructureViews = new ArrayList<>();
		for (UserStructureView userStructureView : userStructureViewMap.values()) {
			if (null == userStructureView.getParent())
				userStructureViews.add(userStructureView);
		}
		return userStructureViews;
	}

}
